//
//  UIDevice+QTZ.m
//  QTZ
//
//  Created by ski on 2017/7/5.
//  Copyright © 2017年 ski. All rights reserved.
//

#import "UIDevice+QTZ.h"

#import "NSString+QTZ.h"
#import "AFNetworking.h"
#import <AdSupport/AdSupport.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <CoreTelephony/CTCarrier.h>

@implementation UIDevice (QTZ)

+ (NSString *)QTZ_deviceName
{
    static NSString *deviceName = nil;
    
    if (!deviceName) {
        
        deviceName = [[[self currentDevice] name] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        
        if( [@"i386" isEqualToString:deviceName] || [@"x86_64" isEqualToString:deviceName] ) {
            deviceName = @"iOS_Simulator";
        }
        
        
    }
    
    return deviceName;
}

+ (NSString *)QTZ_uniqueID
{
    static NSString *kXSJUniqueIDKey = @"XSJ_unique_key";
    NSString *uniqueId = @"";
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
        if (NSClassFromString(@"ASIdentifierManager")) {
            if ([ASIdentifierManager sharedManager].isAdvertisingTrackingEnabled) {
                uniqueId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
            }
        }
        
        if ( IsEmptyString(uniqueId) ) {//不存在说明用户关闭了广告跟踪
            uniqueId = [[NSUserDefaults standardUserDefaults] objectForKey:kXSJUniqueIDKey];
            if (!uniqueId) {
                NSString *timeString = [NSString stringWithFormat:@"%.5f",[[NSDate date] timeIntervalSince1970]];
                NSString *randomString = [NSString stringWithFormat:@"%d", arc4random() % 10000/*0-9999*/];
                
                uniqueId = [[timeString stringByAppendingString:randomString] MD5];
                
                [[NSUserDefaults standardUserDefaults] setObject:uniqueId forKey:kXSJUniqueIDKey];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }
        }
    }
    else
    {
        uniqueId = [[self QTZ_macAddress] MD5];
    }
    return uniqueId;
}

+ (BOOL)QTZ_isJailbroken
{
    BOOL jailbroken = NO;
    NSString *cydiaPath = @"/Applications/Cydia.app";
    NSString *aptPath = @"/private/var/lib/apt/";
    if ([[NSFileManager defaultManager] fileExistsAtPath:cydiaPath]) {
        jailbroken = YES;
    }
    if ([[NSFileManager defaultManager] fileExistsAtPath:aptPath]) {
        jailbroken = YES;
    }
    return jailbroken;
}

+ (NSString *)QTZ_systemVersion
{
    return [[UIDevice currentDevice] systemVersion];
}

+ (NSString *)QTZ_cellularProvider
{
    CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
    CTCarrier *carrier = info.subscriberCellularProvider;
    NSString *carrierName = [carrier carrierName];
    return carrierName ? : @"";
}


+ (NSInteger)QTZ_networkRadioType
{
    CTTelephonyNetworkInfo *networkInfo = [CTTelephonyNetworkInfo new];
    NSString *radioType = networkInfo.currentRadioAccessTechnology;
    
    //    CORETELEPHONY_EXTERN NSString * const CTRadioAccessTechnologyGPRS
    //    CORETELEPHONY_EXTERN NSString * const CTRadioAccessTechnologyEdge
    //    CORETELEPHONY_EXTERN NSString * const CTRadioAccessTechnologyWCDMA
    //    CORETELEPHONY_EXTERN NSString * const CTRadioAccessTechnologyHSDPA
    //    CORETELEPHONY_EXTERN NSString * const CTRadioAccessTechnologyHSUPA
    //    CORETELEPHONY_EXTERN NSString * const CTRadioAccessTechnologyCDMA1x
    //    CORETELEPHONY_EXTERN NSString * const CTRadioAccessTechnologyCDMAEVDORev0
    //    CORETELEPHONY_EXTERN NSString * const CTRadioAccessTechnologyCDMAEVDORevA
    //    CORETELEPHONY_EXTERN NSString * const CTRadioAccessTechnologyCDMAEVDORevB
    //    CORETELEPHONY_EXTERN NSString * const CTRadioAccessTechnologyeHRPD
    //    CORETELEPHONY_EXTERN NSString * const CTRadioAccessTechnologyLTE
    
    NSInteger networkRadioType = 0;
    
    if ( [radioType isEqualToString:@"CTRadioAccessTechnologyGPRS"]) {
        networkRadioType = 1;
    } else if ( [radioType isEqualToString:@"CTRadioAccessTechnologyEdge"]) {
        networkRadioType = 2;
    } else if ( [radioType isEqualToString:@"CTRadioAccessTechnologyWCDMA"]) {
        networkRadioType = 3;
    } else if ( [radioType isEqualToString:@"CTRadioAccessTechnologyHSDPA"]) {
        networkRadioType = 4;
    } else if ( [radioType isEqualToString:@"CTRadioAccessTechnologyHSUPA"]) {
        networkRadioType = 5;
    } else if ( [radioType isEqualToString:@"CTRadioAccessTechnologyCDMA1x"]) {
        networkRadioType = 6;
    } else if ( [radioType isEqualToString:@"CTRadioAccessTechnologyCDMAEVDORev0"]) {
        networkRadioType = 7;
    } else if ( [radioType isEqualToString:@"CTRadioAccessTechnologyCDMAEVDORevA"]) {
        networkRadioType = 8;
    } else if ( [radioType isEqualToString:@"CTRadioAccessTechnologyCDMAEVDORevB"]) {
        networkRadioType = 9;
    } else if ( [radioType isEqualToString:@"CTRadioAccessTechnologyeHRPD"]) {
        networkRadioType = 10;
    } else if ( [radioType isEqualToString:@"CTRadioAccessTechnologyLTE"]) {
        networkRadioType = 11;
    }
    
    return networkRadioType;
}

+ (NSString *)QTZ_IDFA
{
    NSString *idfa = nil;
    if (NSClassFromString(@"ASIdentifierManager")) {
        if ([ASIdentifierManager sharedManager].isAdvertisingTrackingEnabled) {
            idfa = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
        }
    }
    return idfa;
}

+ (NSString *)QTZ_IDFV
{
    if([[self currentDevice] respondsToSelector:@selector( identifierForVendor)]) {
        return [[self currentDevice].identifierForVendor UUIDString];
    }
    
    return @"";
}

+ (AFNetworkReachabilityStatus)XSJ_networkStatus
{
    return [[AFNetworkReachabilityManager sharedManager] networkReachabilityStatus];
}

+ (CGSize)QTZ_screenPixelSize
{
    CGSize size = [[UIScreen mainScreen] bounds].size;
    size = CGSizeMake(size.width * [UIScreen mainScreen].scale, size.height * [UIScreen mainScreen].scale);
    return size;
}

+ (NSString *)QTZ_macAddress
{
    int                 mib[6];
    size_t              len;
    char                *buf;
    unsigned char       *ptr;
    struct if_msghdr    *ifm;
    struct sockaddr_dl  *sdl;
    
    mib[0] = CTL_NET;
    mib[1] = AF_ROUTE;
    mib[2] = 0;
    mib[3] = AF_LINK;
    mib[4] = NET_RT_IFLIST;
    
    if ((mib[5] = if_nametoindex("en0")) == 0) {
        printf("Error: if_nametoindex error\n");
        return NULL;
    }
    
    if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 1\n");
        return NULL;
    }
    
    if ((buf = malloc(len)) == NULL) {
        printf("Could not allocate memory. error!\n");
        return NULL;
    }
    
    if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 2");
        free(buf);
        return NULL;
    }
    
    ifm = (struct if_msghdr *)buf;
    sdl = (struct sockaddr_dl *)(ifm + 1);
    ptr = (unsigned char *)LLADDR(sdl);
    NSString *outstring = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X",
                           *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
    free(buf);
    
    return outstring;
}

@end
